<?php
namespace App\Repositories;

use App\Helper\Utils;
use App\Traits\SingletonTrait;
use Hyperf\DbConnection\Db;
use App\Model\SysConfig;

class SysConfigRepository extends AbstractRepository
{
    use SingletonTrait;
    public function model()
    {
        return 'App\\Model\\SysConfig';
    }

    public function get(array $names=[]){
        if(empty($names)){
            return [];
        }
        $result = $this->model()::query()->whereIn('name',$names)->get();
        $return=[];
        if($result){
            foreach ($result as $item){
                $return[$item->name]=$item->value;
            }
        }
        return $return;
    }

    public function store($datas)
    {
        $content_arr=[
            'AGENT_AGREEMENT',
            'COMMISSION_RULE'
        ];
        $img_arr=[
            'AGENT_QRCODE'
        ];
        foreach ($datas as $key=>$data){
            if(!is_array($data)){
                if($key!='_token' && $key!='file'){
                    $model = SysConfig::where('type',$key)
                        ->where('name',$key)->first();
                    if(!$model){
                        $model = new SysConfig();
                    }
                    $model->type = 'site';
                    $model->name = $key;
                    if(in_array($key,$content_arr)){
                        $model->value = Utils::stripContentImgPrefix($data);
                    }elseif(in_array($key,$img_arr)){
                        $model->value = str_replace(config('common.image_prefix'),'',$data);
                    }else{
                        $model->value = $data;
                    }
                    $model->save();
                }

            }else{
                foreach ($data as $k=>$v){
                    $model = SysConfig::where('type',$key)
                        ->where('name',$k)->first();
                    if(!$model){
                        $model = new SysConfig();
                        $model->type = $key;
                        $model->name = $k;
                        $model->value = in_array($key,$content_arr)?Utils::stripContentImgPrefix($v):$v;
                        $model->save();
                    }else{
                        SysConfig::where('type',$key)
                            ->where('name',$k)
                            ->update(['value'=>$v]);
                    }
                }
            }
            return $this->success([]);
        }
    }
}